package d2;

import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.request.OapiGettokenRequest;
import com.dingtalk.api.response.OapiGettokenResponse;
import com.taobao.api.ApiException;

public class Test {
	
	private String appKey = "xxxxxxxxxxx";
	private String appSecret = "xxxxxxxxxxx";
	private String accessToken = null;
	private long validTime = 0L;
	private static final long TOKEN_VALID_INTERVAL = 7200 * 1000L; // access tokenの有効期間7200s
	
	
	public String getAccessToken()
			throws ApiException
	{
		long currentTime = System.currentTimeMillis();
		
		if(currentTime < validTime)
		{
			return accessToken;
		}
		DefaultDingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/gettoken");
		OapiGettokenRequest request = new OapiGettokenRequest();
		request.setAppkey(appKey);
		request.setAppsecret(appSecret);
		request.setHttpMethod("GET");
		OapiGettokenResponse response = client.execute(request);	
		accessToken = response.getAccessToken();
		validTime = currentTime + TOKEN_VALID_INTERVAL;
		return accessToken;
	}
	
	public static void main(String[] args)
	{
		Test t = new Test();
		try {
			String token = t.getAccessToken();
			System.out.println(token);
		} catch (ApiException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
